﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using ZhongJia.Lock.Core.Data;
using ZhongJia.Lock.DataMigration.Seeders;
using ZhongJia.Lock.Infrastructure.Data;

namespace ZhongJia.Lock.DataMigration
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 .AddCommandLine(args)
                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            var configuration = builder.Build();
            var connectString = configuration["conn"] ?? configuration.GetConnectionString("lock");
            var services = new ServiceCollection()
                        .AddLogging()
                        .AddEntityFramework()
                        .AddDbContext<LockDbContext>(option =>
                        {
                            option.UseSqlServer(connectString);
                        });

           
            services.AddIdentityServer()
                .AddTemporarySigningCredential()
                .AddConfigurationStore(b => b.UseSqlServer(connectString, options =>
                {
                    options.MigrationsAssembly("ZhongJia.Lock.DataMigration");
                }))
                .AddOperationalStore(b => b.UseSqlServer(connectString, options =>
                {
                    options.MigrationsAssembly("ZhongJia.Lock.DataMigration");
                }));

            services.AddScoped<ISeeder, IdentitySeeder>();
            services.AddSingleton<IDatabaseInitializer, DatabaseInitializer>();
            var serviceProvider = services.BuildServiceProvider();
            var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
            loggerFactory.AddConsole(minLevel: LogLevel.Information);

            var databaseInitializer = serviceProvider.GetService<IDatabaseInitializer>();
            databaseInitializer.Seed(configuration).Wait();
            Console.WriteLine("数据生成成功");
        }
    }
}